﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using DG.Tweening;

public class DragPlate : EventBehaviour {
    public float height = 0.5f;

    Transform _transform;
    Vector3 _screenPos;
    Vector3 _originPos;
    Camera _camera;
    bool _canFalling;
    bool _isDraging;

    static bool _isMoving;

    void Start() {
        _transform = GetComponent<Transform>();
        _camera = _transform.root.GetComponentInChildren<Camera>();
        _originPos = _transform.position;
        _isMoving = false;
	}

    void OnTriggerEnter(Collider other) {
        _canFalling = true;
    }

    void OnTriggerExit(Collider other) {
        _canFalling = false;
    }

    public override void OnPointerClick(PointerEventData eventData) {
        if (!_isDraging && !_isMoving) {
            _isMoving = true;
            OnFinished(() => _isMoving = false);
        }
    }

    public override void OnBeginDrag(PointerEventData eventData) {
        if (_isMoving) {
            return;
        }

        _isDraging = true;
        _screenPos = _camera.WorldToScreenPoint(_transform.position + (Vector3.up * height));
    }

    public override void OnDrag(PointerEventData eventData) {
        if (_isMoving) {
            return;
        }

        var mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, _screenPos.z);
        var worldPos = _camera.ScreenToWorldPoint(mousePos);
        _transform.position = worldPos;
    }

    static int _plateCount;

    public override void OnEndDrag(PointerEventData eventData) {
        _isDraging = false;

        if (_canFalling) {
            _isMoving = true;
            OnFinished(() => _isMoving = false);
        } else {
            _transform.DOMove(_originPos, 0.5f);
        }
    }

    void OnFinished(System.Action callback) {
        var parentName = "Pan(Clone)";
        var axis = Vector3.forward;

        if (ChineseRestaurantManager.Instance.currentDishName == DishName.QingCaiDouFuTang) {
            parentName = "Stockpot(Clone)";
            axis = Vector3.back;
        }

        var parent = _transform.root.Find(parentName);

        if (parentName == "Pan(Clone)") {
            parent = parent.Find("Body");
        }

        var endPos = parent.position + (Vector3.up * height);

        _transform.DOMove(endPos, 0.5f).OnComplete(() => {
            _transform.DOLocalRotate(axis * 150f, 0.5f).OnComplete(() => {
                if (callback != null) {
                    callback();
                }

                Destroy(_transform.GetChild(0).gameObject);

                // 销毁盘子
                _transform.DOMoveY(3f, 1f).OnComplete(() => Destroy(gameObject));

                for (var i = _transform.childCount - 1; i >= 0; i--) {
                    var child = _transform.GetChild(i);

                    if (!child.name.EndsWith("_collider")) {
                        child.SetParent(parent);
                        child.gameObject.AddComponent<DishController>();
                        child.gameObject.AddComponent<CookingFX>();
                        child.gameObject.AddComponent<FallingResetPos>();
                    }
                }

                SplashFX.ShowSplash = true;

                if (ChineseRestaurantManager.Instance.currentDishName == DishName.QingCaiDouFuTang) {
                    AudioManager.Instance.PlaySound(ChineseRestaurantResPath.SFX_FOOD_FALLING_WATER);
                    FindObjectOfType<StockpotController>().waterRenderer.GetComponent<Collider>().enabled = true;
                } else {
                    if (SwitchController.IsOn) {
                        AudioManager.Instance.PlaySound(ChineseRestaurantResPath.SFX_FOOD_FALLING_OIL);
                    }
                }

                _plateCount += 1;

                if (_plateCount >= ChineseRestaurantManager.Instance.GetFoodMaterialFromCurrentDishName().Length) {
                    parent.Find("Collider").SetActive(false);

                    if (ChineseRestaurantManager.Instance.currentDishName == DishName.QingCaiDouFuTang) {
                        int floaterCount = 6;
                        var rigidbodies = new List<Rigidbody>(parent.GetComponentsInChildren<Rigidbody>());

                        while (floaterCount > 0) {
                            var index = Random.Range(0, rigidbodies.Count);
                            var t = rigidbodies[index];
                            var floater = t.GetComponent<FloaterByPhysics>();

                            if (floater == null) {
                                floater = t.gameObject.AddComponent<FloaterByPhysics>();
                                floater.waterLevel = 1.4f;
                                ChineseRestaurantManager.Instance.FloaterList.Add(floater);

                                if (SwitchController.IsOn) {
                                    floater.enabled = false;
                                }
                            }

                            floaterCount -= 1;
                        }
                    } 

                    // 显示调料
                    FindObjectOfType<LevelSecond>().ShowCondiment();
                    _plateCount = 0;
                }
            });
        });
    }
}
